package com.xbf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbf.dto.CartGoodsDTO;
import com.xbf.entity.Goods;
import com.xbf.entity.Shop;
import com.xbf.mapper.ShopMapper;
import com.xbf.service.GoodsService;
import com.xbf.service.ShopService;
import org.springframework.stereotype.Service;


import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements ShopService {

    private final GoodsService goodsService;

    public ShopServiceImpl(GoodsService goodsService) {
        this.goodsService = goodsService;
    }

    @Override
    public boolean addToCart(Shop shop) {
        // 检查购物车中是否已存在该商品
        Shop existShop = lambdaQuery()
                .eq(Shop::getUId, shop.getUId())
                .eq(Shop::getGId, shop.getGId())
                .one();

        if (existShop != null) {
            // 已存在，增加数量
            existShop.setSNum(existShop.getSNum() + shop.getSNum());
            existShop.setSPrice(existShop.getSPrice() + shop.getSPrice());
            return updateById(existShop);
        } else {
            // 不存在，新增记录
            return save(shop);
        }
    }

    @Override
    public List<Shop> getCartByUserId(Integer userId) {
        return lambdaQuery()
                .eq(Shop::getUId, userId)
                .list();
    }

    @Override
    public boolean updateCartItem(Shop shop) {
        return updateById(shop);
    }

    @Override
    public boolean deleteCartItem(Integer id) {
        return removeById(id);
    }

    @Override
    public List<CartGoodsDTO> getCartGoods(Integer userId) {
        List<Shop> cartItems = getCartByUserId(userId);
        return cartItems.stream().map(item -> {
            Goods goods = goodsService.getById(item.getGId());
            CartGoodsDTO dto = new CartGoodsDTO();
            dto.setSId(item.getSId());
            dto.setGName(goods.getGName());
            dto.setGPrice(goods.getGPrice());
            dto.setSNum(item.getSNum());
            dto.setTotal(goods.getGPrice() * item.getSNum()); // 计算单项总价
            return dto;
        }).collect(Collectors.toList());
    }
}